package cn.xu.bookstore.user.service;

import cn.xu.bookstore.user.dao.UserDao;
import cn.xu.bookstore.user.domain.User;
import cn.xu.bookstore.user.exception.UserException;
//处理一些有关数据库的逻辑判断
public class UserService {
	private UserDao userDao = new UserDao();
	
	/*
	 * 判断 用户名和邮箱是否注册 诺注册则抛出异常
	 * 否则则 添加用户
	 */
	public void regist(User form) throws UserException{
		//验证用户名
		User user = userDao.findByUsername(form.getUsername());
		if(user !=null) throw new UserException("用户名已经注册！");
		//验证邮箱
		user = userDao.findByEmail(form.getEmail());
		if(user !=null) throw new UserException("Email已经注册");
		
		userDao.add(form);
		
	}
	
	/*
	 * 根据激活码查询用户
	 */
	public void active(String code)throws UserException{
		User user = userDao.findByCode(code);
		
		if(user==null) throw new UserException("该激活码无效");
		if(user.getState()) throw new UserException("你已经激活了,不需要在激活了!");
		
		//修改用户的状态
		userDao.updateState(user.getUid(),true);
	}
	
	/*
	 * 用户登录
	 */
	public User login(User form)throws UserException{
		User user = userDao.findByUsername(form.getUsername());
		if(user == null){
			throw new UserException("该用户不存在");
		} 
		if(!user.getPassword().equals(form.getPassword())){
			throw new UserException("密码不正确");
		} 
		if(!user.getState()){
			throw new UserException("用户尚未激活,请去邮箱激活");
		}
		
		return user ;
	}
	
	
	

}
